<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showAddTrademark"
          >添加
        </el-button>
      </div>
    </template>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column
        align="center"
        label="序号"
        type="index"
        width="50"
      ></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌logo">
        <template v-slot="{ row }">
          <img style="width: 100px" :src="row.logoUrl" alt="" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="{ row }">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑品牌"
            placement="top"
          >
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="toEditTrademarkInfo(row)"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除品牌"
            placement="top"
          >
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="toRemoveTrademark(row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper,  ->, sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 弹出对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademarkInfo.id ? '更新' : '添加'}品牌`"
    >
      <el-form :model="trademarkInfo" ref="trademarkFormRef" :rules="rules">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            v-model="trademarkInfo.tmName"
            autocomplete="off"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkInfo.logoUrl"
              :src="trademarkInfo.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png等图片格式,且大小不超过2mb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 取消和确定 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm(trademarkFormRef)">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
export default {
  name: 'Trademark',
};
</script>
<script lang="ts" setup>
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { onMounted, ref, reactive } from 'vue';
import {
  reqGetTrademarkListData,
  reqSaveTrademarkInfo,
  reqRemoveTrademarkInfo,
  reqUpdateTrademarkInfo,
} from '@/api/product/trademark';
import type {
  TrademarkInfoModel,
  TrademarkListModel,
} from '@/api/product/model/trademarkModel';
import { ElMessage, ElMessageBox } from 'element-plus';

import type { UploadProps } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
const trademarkFormRef = ref<FormInstance>();

const currentPage = ref(1);

const pageSize = ref(3);
const total = ref(0);
const small = ref(false);
const loading = ref(true);
const background = ref(false);
const disabled = ref(false);
const trademarkList = ref<TrademarkListModel>([]); //为了保证响应式效果

const dialogTableVisble = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = '140px';

const BASE_URL = import.meta.env.VITE_API_URL;

const initTrademarkInfo = () => ({
  tmName: '',
  logoUrl: '',
});
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在2到6个字符之间', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '请至少上传一张图片',
      trigger: 'change',
    },
  ],
});

const trademarkInfo = reactive<TrademarkInfoModel>(initTrademarkInfo());

const imageUrl = ref('');

//当页面挂载完毕以后就需要去调用
onMounted(() => {
  getTrademarkListData();
});

//1. 获取品牌数据列表
const getTrademarkListData = async () => {
  loading.value = true; //一发请求就需要有一个loading效果
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  );

  trademarkList.value = result.records;
  total.value = result.total;

  //去掉loading效果
  loading.value = false;
};

//2. 实现分页功能，单击页码跳转
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getTrademarkListData();
};

//3. 修改每页显示的数量
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; //切换每页显示数量的时候，需要默认跳转到第一页
  getTrademarkListData();
};

//4. 图片上传前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //console.log(rawFile);
  const imgArr = ['image/jpeg', 'image/png']; //命名图片允许的类型
  if (!imgArr.includes(rawFile.type)) {
    ElMessage.error('图片格式只能是JPEG,jpg,png...请重新选择');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片的大小不能超过2MB!');
    return false;
  }
  return true;
};

//5. 图片上传成功后实现预览及图片地址收集
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  trademarkInfo.logoUrl = response.data; //将图片在服务器端的地址储存到此对象的logoUrl中
};
// 清除图片的校验提示
trademarkFormRef.value?.clearValidate(['logoUrl']);

//6. 添加品牌
// const btnTrademark = async () => {
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    // console.log('vv', valid, fields);
    if (valid) {
      if (trademarkInfo.id) {
        await reqUpdateTrademarkInfo(trademarkInfo);
      } else {
        await reqSaveTrademarkInfo(trademarkInfo);
        // 跳转到第1页
        currentPage.value = 1;
      }

      // 提示用户操作成功
      ElMessage.success('操作品牌成功了...');
      getTrademarkListData();
      // 关闭对话框
      dialogFormVisible.value = false;
    } else {
      console.log('error submit!', fields);
    }
  });
};

//7. 单击添加按钮时弹出对话框，同时清除之前的数据
// 清除校验提示
trademarkFormRef.value?.clearValidate();

const showAddTrademark = () => {
  trademarkInfo.logoUrl = '';
  trademarkInfo.tmName = '';
  // imageUrl.value = '';

  //删除更新时的ID
  delete trademarkInfo.id;
  dialogFormVisible.value = true;
};

//8. 删除trademark数据
const toRemoveTrademark = (row: TrademarkInfoModel) => {
  ElMessageBox.confirm(`您真的要删除${row.tmName}品牌吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await reqRemoveTrademarkInfo(row.id as number);
      ElMessage({
        type: 'success',
        message: '删除品牌成功了',
      });
      // 重新刷新页面
      getTrademarkListData();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      });
    });
};
//9. 去编辑数据  也就是说在单击编辑按钮 的时候要弹出对话框 并将要编辑的数据显示在对话框上
const toEditTrademarkInfo = (row: TrademarkInfoModel) => {
  // 1. 实现数据回显
  Object.assign(trademarkInfo, row);
  // 2. 对话框要显示出来
  dialogFormVisible.value = true;
  // 3. 清除所有的校验提示信息
  trademarkFormRef.value?.clearValidate();
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
